package com.luojun.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.luojun.entity.Commodity;

/**
 * Servlet implementation class DoUpLoad
 */
@WebServlet("/DoUpLoad")
public class DoUpLoad extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DoUpLoad() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String name = "";
		String describe = "";
		String price = "";
		String picture = "";

			// 1 创建管理磁盘的工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 2创建处理文件和解析文件的类
			ServletFileUpload upload = new ServletFileUpload(factory);
			try {
				// 3解析表单里面的每一个元素
				List<FileItem> list = upload.parseRequest(request);
			
				for (FileItem fileItem : list) {
					
					if (fileItem.isFormField()) { // 判断是普通元素，还是文件元素
						if (fileItem.getFieldName().equals("name")) {
							name = fileItem.getString("utf-8");// 防止中文乱码
						} else if (fileItem.getFieldName().equals("describe")) {
							describe = fileItem.getString("utf-8");
						} else if(fileItem.getFieldName().equals("price")){
							price = fileItem.getString();
						}
						
					} else {
					
						String fileName = fileItem.getName();

						long size = fileItem.getSize();
						if (size == 0 || fileName == null) {
							return;
						}					
						picture = request.getServletContext().getRealPath("/")+
								"static/img/" + fileName;
					
						File file = new File(picture);
						fileItem.write(file);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
}
